package com.cl.it.spider;

import com.cl.it.mbg.entity.Company;
import com.cl.it.mbg.entity.News;
import com.cl.it.utils.DateUtils;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class JiemianSpider extends AbstractSpider{

    @Override
    protected void executeSingleCompany(WebDriver driver, WebDriverWait wait, Company company) {
        String url = "https://a.jiemian.com/index.php?m=search&a=index&msg=###&type=news";
        url = url.replace("###", company.getShortName());
        driver.get(url);
        String listCssSelector = "div.content div.list-search-news>div.news-view";
        if (!has(driver, listCssSelector)) {
            return;
        }
        List<WebElement> articles = selectors(driver, listCssSelector);
        for (int i = 0; i < articles.size(); i++) {
            WebElement element = articles.get(i);
            News news = new News();
            news.setTitle(selectorText(element, "div.news-header"));
            news.setContent(selectorText(element, "div.news-main"));
            news.setSourceUrl(selector(element, "div.news-header a").getAttribute("href"));
            news.setNewsDate(DateUtils.dateConvert(selectorText(element, "div.news-footer span.date")));
            news.setSource(selectorText(element, "div.news-footer span.author"));
            news.setDataSource("界面");

            UpdateWrapper<News> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("title", news.getTitle());
            updateWrapper.eq("name", news.getName());
            newsService.saveOrUpdate(news, updateWrapper);
        }
    }

    @Override
    protected void login(WebDriver driver, WebDriverWait wait) {

    }
}
